package errcode

import (
	"fmt"
	"io"
	"strconv"
	"strings"
)

// ErrCode 错误码
type ErrCode int

// Error 实现error接口
func (e ErrCode) Error() string {
	return GetCodeString(e)
}

// Format 实现Formatter接口
func (e ErrCode) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			value, ok := ShouldGetCodeString(e)
			if ok {
				io.WriteString(s, value)
				io.WriteString(s, "(")
				io.WriteString(s, e.ToString())
				io.WriteString(s, ")")
				return
			}
			io.WriteString(s, e.GetDefaultCodeString())
			return
		}
		fallthrough
	case 's', 'q':
		io.WriteString(s, e.Error())
	}
}

// GetDefaultCodeString 获取错误码的默认字符串
func (e ErrCode) GetDefaultCodeString() string {
	buf := strings.Builder{}

	buf.WriteString("ErrCode(")
	buf.WriteString(e.ToString())
	buf.WriteString(")")

	return buf.String()
}

// ToString 转换为字符串
func (e ErrCode) ToString() string {
	return strconv.Itoa(int(e))
}

// GetCode 获取错误码
func (e ErrCode) GetCode() int {
	return int(e)
}

// GetMessage 获取消息
func (e ErrCode) GetMessage() string {
	return GetCodeString(e)
}

// GetCodeString 获取字符串
func (e ErrCode) GetCodeString() string {
	value, _ := ShouldGetCodeString(e)
	return value
}
